//查找字符串中是否包含单词
function contains(str, word) {
  return str.indexOf(word) > -1;
}
// choose_img 点击时触发 iptfile的click事件
var choose_img = document.querySelector(".choose_img");
choose_img.addEventListener("click", function () {
  $("#iptfile").click();
});

//获取用户信息 并且展示出来
var user_username = document.querySelector("#user_username");
var user_nickname = document.querySelector("#user_nickname");
var user_email = document.querySelector("#user_email");
var user_btn = document.querySelector("#user_btn");
var userimg = document.querySelector(".userimg");
//fetch 获取用户信息
var myHeaders = new Headers();
myHeaders.append("Authorization", localStorage.getItem("token"));

var urlencoded = new URLSearchParams();

var requestOptions = {
  method: "GET",
  headers: myHeaders,
  redirect: "follow",
};

fetch(`${apirUrl}/my/userinfo`, requestOptions)
  .then((response) => response.json())
  .then((result) => {
    console.log(result);
    if (result.status == 0) {
      user_username.value = result.data.username;
      user_nickname.value = result.data.nickname;
      user_email.value = result.data.email;
      userimg.src = apirUrl + result.data.userimg;
    } else if (result.status == 1) {
      me_uto.innerHTML = "身份认证失败";
      toast_body.innerHTML = "身份认证失败！即将跳转到登录界面！";
      toast.show();
      setTimeout(function () {
        location.href = serverUrl + "/login.html";
      }, 2000);
    }
  })
  .catch((error) => console.log("error", error));

var imgsrc = "";
var userimg = document.querySelector(".userimg");
iptfile.addEventListener("change", function (e) {
  e.preventDefault();
  var formData = new FormData();
  formData.append("file", iptfile.files[0]);
  // formData.append("text", document.getElementById("textS").value);
  axios.post(apirUrl + "/api/uploadimg", formData).then(function (res) {
    console.log(res.data);
    userimg.src = apirUrl + res.data.src;
    me_uto.innerHTML = "头像上传成功";
    toast_body.innerHTML = "头像上传成功，记得连同其他信息一起去保存哟！";
    toast.show();
    imgsrc = res.data.src;
    // console.log(imgsrc);
  });
});

//上传信息
user_btn.addEventListener("click", function () {
  var myHeaders = new Headers();
  myHeaders.append("Authorization", localStorage.getItem("token"));

  var urlencoded = new URLSearchParams();
  urlencoded.append("nickname", user_nickname.value);
  urlencoded.append("email", user_email.value);
  urlencoded.append("userimg", imgsrc);

  var requestOptions = {
    method: "POST",
    headers: myHeaders,
    body: urlencoded,
    redirect: "follow",
  };

  fetch("http://124.221.62.120:3000/my/userinfo", requestOptions)
    .then((response) => response.json())
    .then((result) => {
      console.log(result);
      //   me_uto.innerHTML = "信息修改成功";
      //   toast_body.innerHTML = "信息修改成功！";
      //   toast.show();
      if (result.status == 0) {
        me_uto.innerHTML = "信息修改成功";
        toast_body.innerHTML = "信息修改成功！";
        toast.show();
      } else if (result.status == 1) {
        if (contains(result.message, '"userimg" is not allowed to be empty')) {
          me_uto.innerHTML = "上传失败";
          toast_body.innerHTML = "上传<strong> 头像 </strong>不能为空！";
          toast.show();
        } else if (
          contains(result.message, '"nickname" is not allowed to be empty')
        ) {
          me_uto.innerHTML = "上传失败";
          toast_body.innerHTML = "上传<strong> 昵称 </strong>不能为空！";
          toast.show();
        } else if (
          contains(result.message, '"email" is not allowed to be empty')
        ) {
          me_uto.innerHTML = "上传失败";
          toast_body.innerHTML = "上传<strong> 邮箱 </strong>不能空！";
          toast.show();
        } else if (
          contains(
            result.message,
            '"nickname" length must be at least 2 characters long'
          )
        ) {
          me_uto.innerHTML = "上传失败";
          toast_body.innerHTML =
            "上传<strong> 昵称 </strong>不能少于两个字符！";
          toast.show();
        } else if (contains(result.message, '"email" must be a valid email')) {
          me_uto.innerHTML = "上传失败";
          toast_body.innerHTML = "上传<strong> 邮箱 </strong>格式不正确！";
          toast.show();
        }
      }
    })
    .catch((error) => console.log("error", error));
});

//用户信息和用户密码修改交替
//修改用户信息表单
var form_edit = document.querySelector(".form_edit");
// 修改密码表单
var form_edit_password = document.querySelector(".form_edit_password");
//点击切换到修改密码
var user_send_pw = document.querySelector("#user_send_pw");
//点击切换到修改用户信息
var user_cancel_pwd_btn = document.querySelector("#user_cancel_pwd_btn");
user_send_pw.addEventListener("click", function () {
  form_edit.style.display = "none";
  form_edit_password.style.display = "block";
});
user_cancel_pwd_btn.addEventListener("click", function () {
  form_edit.style.display = "block";
  form_edit_password.style.display = "none";
});

//提交更换密码
var user_submit_pwd = document.querySelector("#user_submit_pwd");
var user_old_pwd = document.querySelector("#user_old_pwd");
var user_new_pwd = document.querySelector("#user_new_pwd");
user_submit_pwd.addEventListener("click", function () {
  var myHeaders = new Headers();
  myHeaders.append("Authorization", localStorage.getItem("token"));

  var urlencoded = new URLSearchParams();
  urlencoded.append("oldPwd", user_old_pwd.value);
  urlencoded.append("newPwd", user_new_pwd.value);

  var requestOptions = {
    method: "POST",
    headers: myHeaders,
    body: urlencoded,
    redirect: "follow",
  };

  fetch(`${apirUrl}/my/updatepwd`, requestOptions)
    .then((response) => response.json())
    .then((result) => {
      console.log(result);
      if (result.status == 0) {
        me_uto.innerHTML = "密码修改成功";
        toast_body.innerHTML = "密码修改成功！";
        toast.show();
      } else if (result.status == 1) {
        if (
          contains(
            result.message,
            `"newPwd" with value "${user_new_pwd.value}" fails to match the required pattern: /^[\\S]{6,12}$/`
          )
        ) {
          me_uto.innerHTML = "修改失败";
          toast_body.innerHTML =
            "<strong>  新密码 </strong>应位<strong> 6-12 </strong>位字符！";
          toast.show();
        } else if (contains(result.message, "原密码错误!")) {
          me_uto.innerHTML = "修改失败";
          toast_body.innerHTML = "<strong>  原密码 </strong>错误！";
          toast.show();
        } else if (
          contains(result.message, '"newPwd" is not allowed to be empty')
        ) {
          me_uto.innerHTML = "修改失败";
          toast_body.innerHTML = "<strong> 新密码 </strong>不能为空！";
          toast.show();
        } else if (
          contains(result.message, '"oldPwd" is not allowed to be empty')
        ) {
          me_uto.innerHTML = "修改失败";
          toast_body.innerHTML = "<strong>  原密码 </strong>不能为空！";
          toast.show();
        } else if (
          contains(
            result.message,
            `"oldPwd" with value "${user_old_pwd.value}" fails to match the required pattern: /^[\\S]{6,12}$/`
          )
        ) {
          me_uto.innerHTML = "修改失败";
          toast_body.innerHTML =
            "<strong>  原密码 </strong>应位<strong> 6-12 </strong>位字符！";
          toast.show();
        }
      }
    })
    .catch((error) => console.log("error", error));
});
